package myJs.search.detail

import myJs.Implicits._
import myJs.api.Api
import myJs.cps._
import myJs.myPkg.{MyFetch, ReactRouterDOM, SwalOptions, layer, swal}
import shared.Pojo._
import myJs.tool.Tool
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks._
import slinky.web.html._

import scala.scalajs.js.Dynamic.{global => g}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.tsPojo.TsPojo
import upickle.default._

import scala.collection.immutable.SeqMap
import typings.csstype.csstypeStrings

/**
 * Created by yz on 21/1/2022
 */
@react object MTissueCp {

  case class Props(geneName: String)

  val groupMap = List("Phenotype", "Model", "Model_duration").optionMap
  val initPhenotypes = List("Fetal", "Normal", "Fatty Liver", "NAFLD", "Viral Hepatitis", "Fibrosis", "HCC", "HB", "Ductular Proliferation", "IPNB", "ICC")

  val component = FunctionalComponent[Props] { props =>

    val (phenotypes, setPhenotypes) = useState(initPhenotypes)
    val (datasets, setDatasets) = useState(List.empty[String])
    val (models, setModels) = useState(List.empty[String])
    val (hasRefreshDatasetMap, setHasRefreshDatasetMap) = useState(false)
    val (hasRefreshModelMap, setHasRefreshModelMap) = useState(false)
    val (group, setGroup) = useState("Phenotype")
    val (imgSrc, setImgSrc) = useState("")
    val (geneName, setGeneName) = useState(props.geneName)
    val (isLog, setIsLog) = useState(false)
    val (datasetMap, setDatasetMap) = useState(SeqMap[String, String]())
    val (modelMap, setModelMap) = useState(SeqMap[String, String]())
    val navigate = ReactRouterDOM.useNavigate()
    val (geneData, setGeneData) = useState("")

    object FTool {

      def refreshImg = () => {
        import TsPojo.browseGene._
        val index = layer.alert(Tool.loadingElement, Tool.layerOptions)
        val log = if (isLog) "Yes" else "No"
        val request = MTissueBoxplotImage.Request(geneName = geneName, phenotypes = phenotypes, group = group,
          datasets = datasets, models = models, log = log)
        Api.browseGene.mTissueBoxplotImage(request).map { response =>
          layer.close(index)
          if (response.valid) {
            val src = s"data:image/png;base64,${response.base64}"
            setImgSrc(src)
            setGeneData(response.geneData)
          } else {
            val options = SwalOptions(title = "Error", text = response.message, `type` = "error")
            swal(options)
          }
        }
        ()
      }

      def isLogChange = (v: Boolean) => {
        setIsLog(v)
      }

      def groupChange = (v: String) => {
        setGroup(v)
      }

      def phenotypesChange = (vs: List[String]) => {
        setPhenotypes(vs)
      }

      def datasetsChange = (vs: List[String]) => {
        setDatasets(vs)
      }

      def modelsChange = (vs: List[String]) => {
        setModels(vs)
      }

      def reset = () => {
        setGroup("Phenotype")
        setPhenotypes(initPhenotypes)
        setDatasets(datasetMap.keyList)
        setModels(modelMap.keyList)
        setIsLog(false)
      }

      def geneNameChange = (v: String) => {
        setGeneName(v)
      }

      def refreshDatasetMap = {
        Api.getFileColumn("mbulk_meta.txt","Dataset").map { rs =>
          val curDatasetMap = rs.optionMap
          setDatasetMap(curDatasetMap)
          setDatasets(curDatasetMap.keyList)
          setHasRefreshDatasetMap(true)
        }
      }

      def refreshModelMap = {
        Api.getFileColumn("mbulk_meta.txt","Model_show").map { rs =>
          val curMap = rs.optionMap
          setModelMap(curMap)
          setModels(curMap.keyList)
          setHasRefreshModelMap(true)
        }
        ()
      }

      def downloadCsv = () => {
        Tool.downloadCsv(s"${props.geneName}.csv", geneData)
      }

      def downloadPng = () => {
        Tool.downloadPng(imgSrc = imgSrc, fileName = s"${props.geneName}.png")
      }

      def downloadJpeg = () => {
        Tool.downloadJpeg(imgSrc = imgSrc, fileName = s"${props.geneName}.jpeg")
      }

      def downloadPdf = () => {
        Tool.downloadPdf(imgSrc = imgSrc, fileName = s"${props.geneName}.pdf")
      }

      def downloadSvg = () => {
        Tool.downloadSvg(imgSrc = imgSrc, fileName = s"${props.geneName}.svg")
      }

    }

    useEffect(() => {
      FTool.refreshDatasetMap
      FTool.refreshModelMap
    }, List()
    )

    useEffect(() => {
      if (hasRefreshDatasetMap && hasRefreshModelMap) {
        FTool.refreshImg()
        setHasRefreshDatasetMap(false)
        setHasRefreshModelMap(false)
      }
    }, List(hasRefreshDatasetMap, hasRefreshModelMap)
    )

    useEffect(() => {
      if (geneName != props.geneName) {
        val url = s"${Detail.absolutePath}?geneName=${geneName}&species=Mmu"
        navigate(s"${url}")
      }
    }, List(geneName)
    )

    div(style := Style(display = csstypeStrings.flex),
      div(style := Style(flex = 3, width = "30%"),
        form(id := "form",
          div(style := Style(marginRight = 15), className := "form-group",
            div(style := Style(),
              label(style := Style(), className := "control-label",
                "Gene Symbol"),
            ),
            div(style := Style(height = 34, display = csstypeStrings.flex, alignItems = csstypeStrings.center),
              {
                val url = s"${Api.apiUrl}/gepLiver/analysis/getAllGene"
                PureAsyncSelect2Cp(width = "100%", onChange = FTool.geneNameChange, value = geneName,url=url)
              }

            )
          ),
          MFilterCp(phenotypes = phenotypes, phenotypesChange = FTool.phenotypesChange, datasets = datasets,
            datasetsChange = FTool.datasetsChange, models = models,
            modelsChange = FTool.modelsChange,
            datasetMap = datasetMap, modelMap = modelMap),

          div(style := Style(marginRight = 15), className := "form-group",
            div(style := Style(),
              label(style := Style(), className := "control-label",
                "Group by"),
            ),
            div(style := Style(height = 34),
              PureSelect2Cp(optionMap = groupMap, value = group, onChange = FTool.groupChange, width = "100%")
            ),
          ),
          div(style := Style(display = csstypeStrings.flex, marginRight = 15, alignItems = csstypeStrings.center), className := "form-group",
            div(style := Style(flex = 2, display = csstypeStrings.flex),
              label(style := Style(), className := "control-label",
                "Log", sub("2"), "(TPM+1):"),
            ),
            div(style := Style(flex = 3, height = 34,
              paddingLeft = 15, paddingRight = 15), className := "col-sm-3",
              PureToggleCp(value = isLog, valueChange = FTool.isLogChange)
            ),
          ),
          div(className := "form-group",
            div(className := "actions",
              button(style := Style(width = "95%"), `type` := "button", className := "btn btn-primary myBtn", onClick := FTool.refreshImg,
                s" Plot",
              ),
            ),
            div(className := "actions",
              button(style := Style(width = "95%"), `type` := "button", className := "btn btn-primary myBtn", onClick := FTool.reset,
                s" Reset",
              ),
            )
          ),

        ),
      ),
      div(style := Style(flex = 7),
        div(style := Style(display = csstypeStrings.flex, justifyContent = csstypeStrings.`flex-end`),
          a(onClick := FTool.downloadCsv, className := "btn  btn-default", title := "Export data",
            i(className := "glyphicon glyphicon-export")
          ),
          div(style := Style(marginLeft = 5), className := "btn-group",
            a(title := "Export image", className := "btn  btn-default idsButton", data - "toggle" := "dropdown",
              data - "hover" := "dropdown", data - "close-others" := "true", aria - "expanded" := "false",
              i(className := "fa fa-bars")
            ),
            ul(className := "dropdown-menu pull-right",
              li(
                a(onClick := FTool.downloadPng, "Download PNG image")
              ),
              li(
                a(onClick := FTool.downloadJpeg, "Download JPEG image")
              ),
              li(
                a(onClick := FTool.downloadPdf, "Download PDF image")
              ),
              li(
                a(onClick := FTool.downloadSvg, "Download SVG image")
              ),
            )
          )

        ),
        img(className := "mySvg", id := "boxplotImg", src := imgSrc),
        OrthologCp(geneName = geneName,species = "Mmu"),
      )
    )


  }

  object STool {

  }

}
